package com.voice.server.connection.map;

import com.voice.core.utils.ResponseUtil;
import com.voice.core.DefaultClient;
import com.voice.core.connection.Connection;
import com.voice.core.connection.entity.StreamData;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

public abstract class ConnectionMap<T extends Connection> extends ConcurrentHashMap<String,T> {

    private DefaultClient defaultClient=new DefaultClient();

    @Override
    public T put(String key, T value) {
        T t=super.get(key);
        if(t!=null) t.close();
        T target=super.put(key,value);
        return target;
    }

    @Override
    public T remove(Object key) {
        return super.remove(key);
    }

    public CompletableFuture<StreamData> sendMessage(String key, String topic,Object data){
        return sendMessage(key,topic,0,data);
    }

    public CompletableFuture<StreamData> sendMessage(String key, String topic, int qos, Object data){
        T t=get(key);
        if(t!=null){
            return defaultClient.sendRequest(t, ResponseUtil.success(topic,qos,data));
        }
        return null;
    }

    @Override
    public T get(Object key) {
        return super.get(key);
    }
}
